We study the problem of finding the worst-case joint distribution of a set of risk factors given prescribed multivariate marginals and a nonlinear loss function. We show that when the risk measure is CVaR, and the distributions are discretized, the problem can be conveniently solved using linear programming technique. The method has applications to any situation where marginals are provided, and bounds need to be determined on total portfolio risk. This arises in many financial contexts, including pricing and risk management of exotic options, analysis of structured finance instruments, and aggregation of portfolio risk across risk types. Applications to counterparty credit risk are emphasized, and they include assessing wrong-way risk in the credit valuation adjustment, and counterparty credit risk measurement. Lastly a detailed application of the algorithm for counterparty risk measurement to a real portfolio case is also presented in this paper.